import os
import xlrd
import subprocess
# 定义函数
def GetPath(path,cmd):
	subPath= path.split("\\")
	subCmd= cmd.split("/")
	print(subCmd)
	print(subPath)
	e =len(subPath)
	s = 0
	newPath = ""
	for v in subCmd:
		if v=="..":
			e=e-1
			s=s+1
	for i in range(0,e):
		if subPath[i]!="":
			newPath=newPath+subPath[i]+"\\"
	for j in range(s,len(subCmd)):
		if subCmd[j]!="":
			newPath=newPath+subCmd[j]+"\\"
	return  newPath




suffix=".json"
path = os.getcwd()    #取得当前路径 
path=GetPath(path,"..")
exportSheetName=0
exportIsY=1
exportCmd=2
exportDataStart=4
exportDataEnd=5
exportSubPath=6
exportMode=7
exportFileName=8
fileRootPath=""

print(path)
wb = xlrd.open_workbook(filename=path+"\\config.xls")#打开文件
sheet = wb.sheet_by_name("Tables")
fileRootPath = str(sheet.cell_value(0, 1)) #x,下，y横
print(fileRootPath)
fileRootPath=GetPath(path,fileRootPath)
print(fileRootPath)

def GetSheetInfo(index):
	sheetName=str(sheet.cell_value(index, exportSheetName))
	isY=str(sheet.cell_value(index, exportIsY))
	cmdI=str(sheet.cell_value(index, exportCmd))
	dataStartI=str(sheet.cell_value(index, exportDataStart))
	dataEndI=str(sheet.cell_value(index, exportDataEnd))
	subPath=str(sheet.cell_value(index, exportSubPath))
	mode=str(sheet.cell_value(index, exportMode))
	fileName=str(sheet.cell_value(index, exportFileName))
	return sheetName,isY,cmdI,dataStartI,dataEndI,subPath,mode,fileName


def isNull(v):
	if v is None or v=="" or v=="nil":
		return True
	return False


def CreateSheet2JsonStr(sheetName,cmdI,dataStartI,dataEndI): #将表转换为json字符串
	types = "["
	fields = "["
	values = "["
	st =  wb.sheet_by_name(sheetName)
	CREATE_X = 1
	while(True):
	  	v = str(st.cell_value(CREATE_X, cmdI))
	  	if v=="CREATE":
	  		break
	  	CREATE_X=CREATE_X+1

	fileName = str(st.cell_value(CREATE_X, cmdI+1))
	FLDTYPE_X = CREATE_X+1

	while(True):
	  	v=str(st.cell_value(FLDTYPE_X, cmdI))
	  	if v=="FLDTYPE":
	  		break
	  	FLDTYPE_X=FLDTYPE_X+1
	#生成types字段
	NullIList = []
	for i in range(dataStartI,dataEndI+1):
		v=str(st.cell_value(FLDTYPE_X, i))
		if v=="N":
			NullIList.append(i)
		else:
			v="\""+v+"\""
			types=types+v+","
	types=types[0:len(types)-1]+"]"

	FLDNAME_X = FLDTYPE_X+1
	while(True):
		v=str(st.cell_value(FLDNAME_X, cmdI))
		if v=="FLDNAME":
			break
		FLDNAME_X=FLDNAME_X+1


	#生成fields字段

	for i in range(dataStartI,dataEndI+1):
		if not i in NullIList:
			v= str(st.cell_value(FLDNAME_X, i))
			v="\""+v+"\""
			fields=fields+v+","

	#fields=string.sub(fields, 1, -2).."]"
	fields=fields[0:len(fields)-1]+"]"

	#生成values字段
	Data_X = FLDNAME_X+1
	while(True):
		t = str(st.cell_value(Data_X, cmdI))
		if t=="DATA":
			data = "["
			for i in range(dataStartI,dataEndI+1):
				if not i in NullIList:
					v = str(st.cell_value(Data_X, i))
					v="\""+v+"\""
					data=data+v+","	
			data=data[0:len(data)-1]+"]"


			values=values+data+","

		elif t=="CLOSE":
			break
		Data_X=Data_X+1

	values=values[0:len(values)-1]+"]"

	#values=string.sub(values, 1, -2)+"]"

	# st:Close()

	json = "{\"types\":"+types+",\"fields\":"+fields+",\"values\":"+values+"}"
	return json,fileName

jsonPath = '../Data/json/'
def CreateSheet2LuaFlie(sheetName,cmdI,dataStartI,dataEndI,mode,fileName,path):
	json,file=CreateSheet2JsonStr(sheetName,cmdI,dataStartI,dataEndI)
	with open(jsonPath+file+".json",'w',encoding='utf-8') as f: # 如果filename不存在会自动创建， 'w'表示写数据，写之前会清空文件中的原有数据！
		f.write(json)


sheetindexStart=2

while(sheetindexStart<sheet.nrows):
	sheetName,isY,cmdI,dataStartI,dataEndI,subPath,mode,fileName=GetSheetInfo(sheetindexStart)
	if isNull(sheetName):
		break
	if not isNull(sheetName) and isY=="Y":
		filePath =fileRootPath
		if not isNull(subPath):
			filePath=GetPath(filePath,subPath)
		flist=None
		if  not isNull(mode):
			print(mode)
		print("正在转化:"+sheetName+"...")

		CreateSheet2LuaFlie(sheetName,int(float(cmdI))-1,int(float(dataStartI))-1,int(float(dataEndI)-1),flist,fileName,filePath)
	sheetindexStart=sheetindexStart+1
import sys
sys.stdout.flush()

result = subprocess.check_output(['lua', '-l', 'Tool', '-e', 'Exportlua()'])
print(result)